//
//  MyCollection.m
//  UESTCPioneer
//
//  Created by 张众 on 3/20/14.
//  Copyright (c) 2014 Sway. All rights reserved.
//

#import "MyCollection.h"
#import "constant.h"
#import "CellWithCustomLeftImageAndLabel.h"
#import "CellWithCustomLeftImageAndLabel.h"
#import "PartyNoticeNewsEntity.h"
@interface MyCollection ()
{
    NSMutableArray *info;
    NSMutableArray *content;
    int page;
}

@end

@implementation MyCollection

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self.view addSubview:self.refreshTableView];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //使用定制的tableview，设置上下拉刷新
    __weak MyCollection* weakSelf =self;
    
    [self.refreshTableView setPullDownBeginRefreshBlock:^(MJRefreshBaseView *refreshView) {
        [weakSelf pullDown:refreshView];
    }];
    
    [self.refreshTableView setPullUpBeginRefreshBlock:^(MJRefreshBaseView *refreshView) {
        [weakSelf pullUp:refreshView];
    }];
    
    info = [[NSMutableArray alloc] init];
    content = [[NSMutableArray alloc] init];
    
    page = 2;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.title = @"我的收藏";
    
    [self.refreshTableView beginRefreshing];
    
    self.leveyTabBarController.navigationItem.title = @"";
    
}

-(void)dealloc{
    [self.refreshTableView freeHeaderFooter];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [info count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"setcell";
    CellWithCustomLeftImageAndLabel *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[CellWithCustomLeftImageAndLabel alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.leftImage.image = [UIImage imageNamed:@"col.png"];
    cell.label.text = [info[indexPath.row] valueForKey:@"title"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view.backgroundColor = ViewControllerBackgroundColor;
    //    UITextView *textview = [[UITextView alloc] initWithFrame:CGRectMake(10, 5, 300, vc.view.frame.size.height - 44- 20)];
    UITextView * textview = [[UITextView alloc] init];
    textview.editable = NO;
    textview.font = [UIFont systemFontOfSize:17];
    [NetworkCenter AFRequestWithData:[RequestData getPerAdminNoticeRequestDataWithNoticeid:[[info[indexPath.row] valueForKey:@"id"] intValue]]  SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        [content removeAllObjects];
        [content addObjectsFromArray:[NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableContainers error:nil]];
        if ([content count] > 0) {
            textview.text = [content[0] valueForKey:@"content"];
        }
        else
        {
            textview.text = @"数据请求错误!";
        }
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"网络请求失败!"];
    }];
    
    [vc.view addSubview:textview];
    vc.navigationItem.title = @"通知内容";
    
    NSLog(@"info[indexPath.row] = %@",info[indexPath.row]);
    NSDictionary *entity = info[indexPath.row];
    
    [vc.view setFrame:self.view.frame];
    [vc.view setBackgroundColor:[UIColor whiteColor]];
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(vc.view.frame.origin.x, vc.view.frame.origin.y, vc.view.frame.size.width, 45)];
    
    NSString *title = entity[@"title"];
    
    label.text = title;
    [label setBackgroundColor:[UIColor whiteColor]];
    [label setFont:[UIFont systemFontOfSize:17]];
    //    [label setTextColor:[UIColor grayColor]];
    //文字居中显示
    label.textAlignment = NSTextAlignmentCenter;
    //自动折行设置
    //    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.numberOfLines = 0;
    label.adjustsFontSizeToFitWidth = YES;
    
    [vc.view addSubview:label];
    [label setTranslatesAutoresizingMaskIntoConstraints:NO];
    [vc.view addConstraint:[NSLayoutConstraint constraintWithItem:label
                                                        attribute:NSLayoutAttributeTop
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:vc.view
                                                        attribute:NSLayoutAttributeTop
                                                       multiplier:1 constant:0]];
    //    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:label
    //                                                            attribute:NSLayoutAttributeLeft
    //                                                            relatedBy:NSLayoutRelationEqual
    //                                                            toItem:viewController.view
    //                                                            attribute:NSLayoutAttributeLeft
    //                                                            multiplier:1 constant:3]];
    //    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:label
    //                                                          attribute:NSLayoutAttributeRight
    //                                                          relatedBy:NSLayoutRelationEqual
    //                                                             toItem:viewController.view
    //                                                          attribute:NSLayoutAttributeRight
    //                                                         multiplier:1 constant:3]];
    [vc.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-3.0-[label]-3.0-|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(label)]];
    [vc.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[label(==45)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(label)]];
    
    NSLog(@"执行了label = %@",label);
    //    [textView setTextColor:[UIColor grayColor]];
    [textview setEditable:NO];
    [textview setScrollEnabled:YES];
    [textview setFont:[UIFont systemFontOfSize:18]];
    [vc.view addSubview:textview];
    [textview setTranslatesAutoresizingMaskIntoConstraints:NO];
    [vc.view addConstraint:[NSLayoutConstraint constraintWithItem:textview
                                                        attribute:NSLayoutAttributeTop
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:label
                                                        attribute:NSLayoutAttributeBottom
                                                       multiplier:1
                                                         constant:0]];
    [vc.view addConstraint:[NSLayoutConstraint constraintWithItem:textview
                                                        attribute:NSLayoutAttributeBottom
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:vc.view
                                                        attribute:NSLayoutAttributeBottom
                                                       multiplier:1
                                                         constant:-5]];
    [vc.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[textview]|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(textview)]];
    //    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[textview(==300)]|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(textView)]];
    
    
    [self.leveyTabBarController.navigationController pushViewController:vc animated:YES];
    [self.refreshTableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

#pragma mark 删除按钮的显示
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCellEditingStyle result = UITableViewCellEditingStyleNone;
    if([tableView isEqual:self.refreshTableView]){
        result = UITableViewCellEditingStyleDelete;
    }
    return result;
}
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    [self.refreshTableView setEditing:editing animated:animated];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(editingStyle == UITableViewCellEditingStyleDelete){
        if(indexPath.row < [info count]){
            
            NSDictionary *CollectReqeustData = @{
                                                 @"type":@"naViewcollect"
                                                 ,@"view_collect":@"0"
                                                 ,@"shoucang":[NSString stringWithFormat:@"%d",0]
                                                 ,@"fromusername":[constant getUserName]
                                                 ,@"fromuserid":[constant getUserId]
                                                 ,@"gonggaoid":[NSString stringWithFormat:@"%@",info[indexPath.row][@"id"]]
                                                 ,@"typepid":@"1"
                                                 };
            
            //             NSDictionary *CollectReqeustData = @{
            //                                                 @"type":@"delePersonColl"
            //                                                 ,@"userid":[constant getUserId]
            //                                                 ,@"noticeid":[NSString stringWithFormat:@"%@",info[indexPath.row][@"id"]]
            //                                                 };
            
            
            [NetworkCenter AFRequestWithData:CollectReqeustData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:Nil];
                if ([dic[@"result"] isEqualToString:@"success"]){
                    [Alert showAlert:@"取消收藏成功!"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationCancelCollect object:info[indexPath.row]];
                    [info removeObjectAtIndex: indexPath.row];
                    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationLeft];
                }
                else {
                    [Alert showAlert:@"取消收藏失败!"];
                }
            } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                [Alert showAlert:@"网络请求错误"];
                NSLog(@"删除个人收藏出错:%@",[error localizedDescription]);
            }];
        }
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

- (PullRefreshTableView *)refreshTableView
{
    if (!_refreshTableView) {
        _refreshTableView = [[PullRefreshTableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height - 44- 20) style:UITableViewStyleGrouped];
        [_refreshTableView registerClass:[CellWithCustomLeftImageAndLabel class] forCellReuseIdentifier:@"setcell"];
        if(IS_IOS7)
            _refreshTableView.separatorInset = UIEdgeInsetsZero;
        _refreshTableView.delegate = self;
        _refreshTableView.dataSource = self;
    }
    return _refreshTableView;
}

-(void)pullDown:(MJRefreshBaseView*)refreshView
{
    [NetworkCenter AFRequestWithData:[RequestData getCollectionRequestDataWithPage:1] SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        [info removeAllObjects];
        [info addObjectsFromArray:[NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableContainers error:nil]];
        [refreshView endRefreshing];
        [self.refreshTableView reloadData];
        page = 2;
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"网络请求失败!"];
        [refreshView endRefreshing];
    }];
}

-(void)pullUp:(MJRefreshBaseView*)refreshView
{
    if ([info count]%10 == 0)//如果一页没填满就不刷新
    {
        [NetworkCenter AFRequestWithData:[RequestData getCollectionRequestDataWithPage:page] SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
            [info addObjectsFromArray:[NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableContainers error:nil]];
            [refreshView endRefreshing];
            [self.refreshTableView reloadData];
            if ([info count] == 0) {
                self.label.text = @"您暂时没有任何收藏!";
            }
            else
            {
                self.label = nil;
            }
            page++;
        } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            [Alert showAlert:@"网络请求失败!"];
            [refreshView endRefreshing];
        }];
    }
    else
        [refreshView endRefreshing];
}

- (UILabel *)label
{
    if (!_label) {
        _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        _label.center = self.refreshTableView.center;
        _label.textAlignment = NSTextAlignmentCenter;
        _label.textColor = [UIColor grayColor];
        [self.refreshTableView addSubview:_label];
    }
    return _label;
}


//-(void)UPTitleCell:(UPTitleCell *)cell CollectButtonClick:(UIButton *)button{
//
//
//    NSDictionary *CollectReqeustData = @{
//                                         @"type":@"naViewcollect"
//                                         ,@"view_collect":@"0"
//                                         ,@"shoucang":[NSString stringWithFormat:@"%d",flag]
//                                         ,@"fromusername":[constant getUserName]
//                                         ,@"fromuserid":[constant getUserId]
//                                         ,@"gonggaoid":[NSString stringWithFormat:@"%d",cell.theId]
//                                         ,@"typepid":@"1"
//                                         };
//
//    [NetworkCenter AFRequestWithData:CollectReqeustData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:Nil];
//        if ([dic[@"result"] isEqualToString:@"success"]){
//
//        }
//        else {
//
//        }
//    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [Alert showAlert:@"发生错误"];
//    }];
//
//}

@end
